package com.lipiao.food.foodFragments;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.lipiao.food.Activity.FoodStepsActivity;
import com.lipiao.food.FoodBean;
import com.lipiao.food.FoodRecycleViewAdapter;
import com.lipiao.food.FoodStepsBean;
import com.lipiao.food.R;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import io.supercharge.shimmerlayout.ShimmerLayout;

public class FoodGodS extends Fragment {

    View rootView;
    static RecyclerView mRecyclerView;
    static FoodRecycleViewAdapter foodRecycleViewAdapter;
    static List<FoodBean> mList = new ArrayList<>();
    static String url5 = "https://home.meishichina.com/show-top-type-recipe-order-chef.html";
    //加载 灰色闪烁
    ShimmerLayout shimmerLayout;

    AlertDialog alertDialog;//模拟加载数据

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.foodfragment_details, container, false);
        initView();
        initListener();
        return rootView;
    }

    private void initView() {
        //加载
        shimmerLayout = rootView.findViewById(R.id.shimmer_layout);
        shimmerLayout.startShimmerAnimation();
        mRecyclerView = rootView.findViewById(R.id.card_list_food_god);
        //瀑布流
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        mRecyclerView.setHasFixedSize(true);
        //平常的水平一个item布局的流
//        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
//        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        initFoodBeanList();
    }

//    /**
//     * 2秒后刷新界面，模拟网络请求
//     */
//    private void requestData() {
//        alertDialog = new AlertDialog.Builder(getContext())
//                .setMessage("模拟请求网络中..")
//                .setTitle("Tips").create();
//        alertDialog.show();
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    Thread.sleep(1000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                handler.sendEmptyMessage(0x123);
//            }
//        }).start();
//    }
//
//    Handler handler = new Handler() {
//        @Override
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//            if (alertDialog != null) alertDialog.hide();
//           //加载..
//        }
//    };

    void initFoodBeanList() {
        mList = new ArrayList<>();
        //含有网络加载，所以开启新线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                //从一个URL加载一个Document对象。
                try {
                    final Document doc = Jsoup.connect(url5).get();
                    final Elements titleAndPic = doc.select("div.pic");// “菜品”名称和它对应的图片都在<div class="pic">中
                    final Elements url = doc.select("div.pic").select("a");//所需链接在<div class="detail">中的<a>标签里面(原博客错误修改为div.pic detail只有部分原址
                    final Elements burden = doc.select("p.subcontent"); // 原料在<p class="subcontent">中

                    //添加数据
                    for (int i = 0; i < 10; i++) {
                        FoodBean element = new FoodBean("" + titleAndPic.get(i).select("a").select("img").attr("data-src"),
                                "" + titleAndPic.get(i).select("a").attr("title"),
                                "" + burden.get(i).text(),
                                "" + url.get(i).attr("href"));
                        mList.add(element);
                    }
                    //实例化MyAdapter并传入mList对象
                    foodRecycleViewAdapter = new FoodRecycleViewAdapter(mList);
                    //自定义点击事件
                    foodRecycleViewAdapter.setOnItemClickListener(new FoodRecycleViewAdapter.OnItemClickListener() {

                        //点击
                        @Override
                        public void onItemClick(View view, final int position) {

                            alertDialog = new AlertDialog.Builder(getContext())
                                    .setMessage("请求网络中..")
                                    .setTitle("Tips").create();
                            alertDialog.show();

                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        Thread.sleep(300);
                                        //首先获取被点击的item的三个属性（教程网站不需直接用，后面用于获取步骤信息时再用）
                                        String picUrl = mList.get(position).getPicUrl();//菜的图片url
                                        String courseUrl = mList.get(position).getCourseUrl();//教程网站
                                        String foodName = mList.get(position).getFoodName();//菜名
                                        String foodMaterials = mList.get(position).getFoodMaterials();//食材
                                        String[] foodInforArr = new String[4];//菜品4个信息：口味 工艺 耗时 难度
                                        List<String> materialQuantityList = new ArrayList<>();//食材数量不同
                                        List<String> stepList = new ArrayList<>();//做法步骤
                                        List<String> stepPicList = new ArrayList<>();//做法步骤对应图片

                                        Document document = Jsoup.connect(courseUrl).get();
                                        //Element introduce = document.getElementById("block_txt1");//有的没有介绍，批量处理会报空指针错误，暂时不加
                                        Elements foodInfor = document.getElementsByClass("category_s1");
                                        Elements materialInfor = document.getElementsByClass("category_s2");
                                        Elements step = document.getElementsByClass("recipeStep_word");
                                        Elements stepPic = document.getElementsByClass("recipeStep_img");
                                        //Log.d("FoodGodS调式", "onItemClick:介绍" + introduce.text());//有的没有介绍，批量处理会报空指针错误
                                        //食材种类数
                                        int num = materialInfor.size() - 4;//与网站HTML标记相关，前四个为菜品信息
                                        //Log.d("FoodGodS调式", "" + num);//调试是否符和预期

                                        //菜品的4个信息
                                        //Log.d("FoodGodS调式", "菜品的4个信息口味工艺耗时难度:");
                                        for (int i = 0; i < 4; i++) {
                                            foodInforArr[i] = foodInfor.get(num + i).select("a").attr("title");
                                            //Log.d("FoodGodS调式", "" + foodInfor.get(num + i).select("a").attr("title"));
                                        }

                                        //原材料的数量信息
                                        for (int i = 0; i < num; i++) {
                                            materialQuantityList.add("" + materialInfor.get(i).text());
                                            //Log.d("FoodGodS调式", "" + materialInfor.get(i).text());
                                        }

                                        //步骤(文字)
                                        for (int i = 0; i < step.size(); i++) {
                                            stepList.add("" + step.get(i).text());
                                            // Log.d("FoodGodS调式", "" + step.get(i).text());
                                        }
                                        //步骤(图片)
                                        for (int i = 0; i < stepPic.size(); i++) {
                                            stepPicList.add("" + stepPic.get(i).select("img").attr("src"));
                                            //Log.d("FoodGodS调式", "" + stepPic.get(i).select("img").attr("src"));
                                        }

                                        //将装备好数据放入
                                        FoodStepsBean foodStepsBean = new FoodStepsBean(picUrl, foodName, foodMaterials, courseUrl,
                                                foodInforArr, materialQuantityList, stepList, stepPicList);

                                        getActivity().runOnUiThread(new Runnable() {
                                            //getActivity().getApplicationContext()
                                            public void run() {
                                                alertDialog.hide();
                                            }
                                        });


                                        //从fragment启动activity，并传递数据
                                        Intent intent = new Intent(getActivity().getApplicationContext(), FoodStepsActivity.class);
                                        intent.putExtra("foodStepInfor", foodStepsBean);
                                        startActivity(intent);

                                    } catch (InterruptedException | IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }).start();
                        }

                        //长按
                        @Override
                        public void onItemLongClick(View view, int position) {
                            Toast.makeText(getContext(), "长按事件：第" + (position + 1) + "个", Toast.LENGTH_SHORT).show();
                        }
                    });

                    //回到主线程更新UI
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //加载
                            shimmerLayout.setVisibility(View.INVISIBLE);
                            //为RecyclerView对象mRecyclerView设置adapter
                            mRecyclerView.setAdapter(foodRecycleViewAdapter);
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }//catch
            }//run
        }).start();//new thread
    }//initFoodBeanList()

    private void initListener() {

    }
}
